﻿/**
 * 动态为表格添加表头搜索功能
 * Created by li on 2017年09月23日19:46:19
 */
/**
 项目JS主入口
 以依赖Layui的layer和form模块为例
 **/
layui.define(['form', 'layer'], function (exports) {
    var form = layui.form, layer = layui.layer;
    var obj = {
        tableIns: undefined,
        searchConfig: undefined,

        init: function (ins) {
            this.tableIns = ins;
            var tempConfig = [];
            if (undefined != this.tableIns) {
                $.each(this.tableIns.config.cols[0], function (i, v) {
                    // console.log(v.field);
                    if (undefined != v.search) {
                        var temp = {
                            'field': v.field,
                            'type': v.search,
                            'text': v.title,
                            'selector': v.searchData || undefined
                        };
                        tempConfig.push(temp);
                    }
                });
                this.searchConfig = tempConfig;
                if (this.searchConfig.length > 0) {
                    var options = '';
                    // 设置检索条目
                    $.each(this.searchConfig, function (i, v) {
                        options += '<option value="' + v.field + '" type="' + v.type + '">' + v.text + '</option>'
                    });
                    var conditionalHtml = this.genConditionalOptions(this.searchConfig[0].type);
                    var searchValueDefault = this.genSearchValue(this.searchConfig[0].type);
                    var searchDivHtml =
                        '<div style="min-width: 490px;min-height:40px">' +
                        '<form class="layui-form layui-form-pane" lay-filter="searchForm" action="" method="post">' +
                        '<div class="layui-form-item" style="margin:7px 0">' +
                        '<div class="layui-input-inline" style="width: 100px">' +
                        '<select name="field" lay-filter="search_field">' +
                        options +
                        '</select>' +
                        '</div>' +
                        '<div class="layui-input-inline" style="width: 100px">' +
                        conditionalHtml +
                        '</div>' +
                        '<div class="layui-input-inline" style="width: 250px" >' +
                        searchValueDefault +
                        '</div>' +
                        '<button class="layui-btn layui-btn-warm" lay-submit="" lay-filter="searchBtn" >查询</button>' +
                        '<a class="layui-btn layui-btn-primary lay-search-more-btn">高级检索</a>' +
                        '<button class="layui-btn " lay-submit="" lay-filter="refreshBtn" ><i class="layui-icon">&#xe669;</i>重置</button >'+
                        '</div>' +
                        '</form>' +
                        '</div>';
                    // 将表单数据放置正确的位置
                    //$(this.tableIns.config.elem).next().prepend(searchDivHtml);
                    $('#searchBar').html(searchDivHtml);
                    //$('.layui-table-body.layui-table-main').height($('.layui-table-body.layui-table-main').height() - 50);
                    // 动态初始化表单数据
                    form.render();
                    // 添加各种数据绑定
                    this.initEvent();
                }

            }
        },
        /**
         * 初始化简单检索事件绑定
         */
        initEvent: function () {
            var that = this;
            // 添加事件绑定效果
            form.on('select(search_field)', function (data) {
                // 获取检索类型
                var type = $(data.elem).find('[value=' + data.value + ']').attr('type');
                $(data.othis).parent().next().html(that.genConditionalOptions(type));
                var extra = undefined;
                $.each(that.searchConfig, function (i, v) {
                    if (data.value == v.field) {
                        if (v.selector) {
                            extra = v.selector;
                        }
                        return;
                    }
                });
                $(data.othis).parent().next().next().html(that.genSearchValue(type, extra));
                form.render();
            });

            form.on('select(search_condition)', function (data) {
                var type = $(data.elem).attr('type');
                var flag = undefined;
                if ('between' == data.value) {
                    flag = true;
                }
                $(data.othis).parent().next().html(that.genSearchValue(type, flag));
                form.render();
            });
            //查询按钮点击
            form.on('submit(searchBtn)', function (data) {
                if ('like' == data.field.conditional) {
                    // 结构为   %XXXX%
                    data.field.value = '%' + data.field.value + '%';
                } else if ('between' == data.field.conditional) {
                    // 结构为   XXX,XXXX
                    data.field.value = data.field.value + ',' + data.field.value1;
                    delete data.field.value1;
                }
                if ('' != data.field.value) {
                    that.tableIns.reload({
                        where: { 'searchParam': JSON.stringify([data.field]) }
                    });
                    //that.init(that.tableIns);
                }
                return false;
            });
            //刷新按钮点击
            form.on('submit(refreshBtn)', function () {
                that.tableIns.reload({
                    where: { 'searchParam':'' }
                });
                that.init(that.tableIns);
                return false;
            });
            // 绑定高级检索按钮点击事件
            $('.lay-search-more-btn').bind('click', function (e) {
                if (that.searchConfig.length > 0) {
                    var formDiv = '';
                    $.each(that.searchConfig, function (i, v) {
                        var lable = '<label class="layui-form-label">' + v.text + '<input style="display: none" name="field" value="' + v.field + '"/></label>';
                        var conditionalHtml = that.genConditionalOptions(v.type, v.field);
                        var searchValue = that.genSearchValue(v.type, v.selector);
                        var inputDiv = '<div class="layui-input-inline" style="width: 100px">' +
                            conditionalHtml +
                            '</div>' +
                            '<div class="layui-input-inline" style="width: auto">' +
                            searchValue +
                            '</div>';

                        formDiv += '<div class="layui-form-item" >' +
                            lable +
                            inputDiv +
                            '</div>';
                    });
                    var html = '<div style="text-align: center;padding: 16px 0"><form action="" method="post" class="layui-form" lay-filter="searchMoreForm">' +
                        formDiv +
                        '<div class="layui-input-inline">' +
                        '<button class="layui-btn layui-btn-warm" lay-submit="" lay-filter="searchMoreBtn" >高级查询</button>' +
                        '<button type="reset" class="layui-btn layui-btn-primary" >重置</button>' +
                        '</div>' +
                        '</form></div>';
                    var complexIndex = layer.open({
                        type: 1,
                        title: '高级检索',
                        area: ['600px', '480px'], //宽高
                        content: html
                    });
                    form.render();
                    that.initMoreEvent();
                }

            });
        },
        /**
         * 初始化高级检索事件绑定
         */
        initMoreEvent: function () {
            var that = this;
            form.on('select(search_condition_moreSearch)', function (data) {
                var type = $(data.elem).attr('type');
                var flag = undefined;
                if ('between' == data.value) {
                    flag = true;
                }
                $(data.othis).parent().next().html(that.genSearchValue(type, flag));
                form.render();
            });
            form.on('submit(searchMoreBtn)', function () {
                var formData = $('form[lay-filter=searchMoreForm]').serializeArray();
                var temp = { 'field': '', 'conditional': '', 'value': '' };
                var tempObj = [];
                for (var i = 0; i < formData.length; i++) {
                    if ("field" == formData[i].name) {
                        temp.field = formData[i].value;
                    } else if ("conditional" == formData[i].name) {
                        temp.conditional = formData[i].value;
                    } else {
                        if ('like' == temp.conditional) {
                            // 结构为   %XXXX%
                            temp.value = '%' + formData[i].value + '%';
                        } else if ('between' == temp.conditional) {
                            // 结构为   XXX,XXXX
                            temp.value = formData[i].value + ',' + formData[i + 1].value;
                            i++;
                        } else {
                            temp.value = formData[i].value;
                        }
                        if ('' != temp.value) {
                            tempObj.push(temp);
                        }
                        temp = { 'field': '', 'conditional': '', 'value': '' };
                    }
                }
                if (tempObj.length > 0) {
                    that.tableIns.reload({
                        where: { 'searchParam': JSON.stringify(tempObj) }
                    });
                    that.init(that.tableIns);
                }
                return false;
            });
        },

        genConditionalOptions: function (type, field) {
            var moreSearchFlag = '';
            if (field == undefined) {
                field = '';
            } else {
                moreSearchFlag = '_moreSearch';
            }
            var selector_prifix = "<select type='" + type + "' name='conditional' field='" + field + "' lay-filter='search_condition" + moreSearchFlag + "'>";
            var selector_suffix = "</select>";
            var options = '';
            switch (type) {
                case "number":
                    options =
                        '<option value="Equal">等于</option>' +
                        '<option value="GreaterThan">大于</option>' +
                        '<option value="LessThan">小于</option>' +
                        '<option value="between">介于</option>';
                    break;
                case "text":
                    options =
                        '<option value="Like">模糊匹配</option>' +
                        '<option value="Equal">精确匹配</option>';
                    break;
                case "time":
                    options =
                        '<option value="LessThan">早于</option>' +
                        '<option value="Equal">等于</option>' +
                        '<option value="GreaterThan">晚于</option>' +
                        '<option value="between">介于</option>';
                    break;
                case "selector":
                    selector_prifix = "<input style='display:none' type='" + type + "' value='Equal' name='conditional' lay-filter='conditional'>";
                    options = '';
                    selector_suffix = "";
                    break;

            }
            return selector_prifix + options + selector_suffix;
        },

        genSearchValue: function (type, extra, isVerisfy) {
            var html = undefined;
            switch (type) {
                case "number":
                    if (undefined != extra && extra) {
                        html = '<div class="layui-inline"><div class="layui-input-inline" style="width: 72px;">' +
                            '<input type="text" name="value" placeholder="输入数值" autocomplete="off" class="layui-input"></div>' +
                            '<div class="layui-form-mid">-</div><div class="layui-input-inline" style="width: 72px;">' +
                            '<input type="text" name="value1" placeholder="输入数值" autocomplete="off" class="layui-input"></div></div>';
                    } else {
                        html = '<input name="value" autocomplete="off" placeholder="请输入搜索关键字" class="layui-input">';
                    }
                    break;
                case "time":
                    if (undefined != extra && extra) {
                        html = '<div class="layui-inline"><div class="layui-input-inline" style="width: 100px;">' +
                            '<input type="text" name="value" placeholder="开始时间" autocomplete="off" class="layui-input" onclick="WdatePicker({el:this,dateFmt:\'yyyy-MM-dd HH:mm:ss\'});"></div>' +
                            '<div class="layui-form-mid">-</div><div class="layui-input-inline" style="width: 100px;">' +
                            '<input type="text" name="value1" placeholder="结束时间" autocomplete="off" class="layui-input" onclick="WdatePicker({el:this,dateFmt:\'yyyy-MM-dd HH:mm:ss\'});"></div></div>';
                    } else {
                        html = '<input name="value" placeholder="yyyy-mm-dd" autocomplete="off" class="layui-input" onclick="WdatePicker({el:this,dateFmt:\'yyyy-MM-dd\'});">';
                    }
                    break;
                case "selector":
                    if (undefined != extra) {
                        html = this.genSearchValueForSelector(extra);
                    } else {
                        html = '';
                    }
                    break;
                default:
                    html = '<input name="value" autocomplete="off" placeholder="请输入搜索关键字" class="layui-input">';
                    break;

            }
            return html;
        },
        genSearchValueForSelector: function (extra) {
            var html = '';
            if (extra == undefined) {
                return html;
            } else {
                var options = '';
                var selector_prifix = "<select name='value'>";
                var selector_suffix = "</select>";
                var tempExtra = extra.replace(/'/g, '"');
                try {
                    var url = eval('(' + tempExtra + ')').url;
                    if (url) {
                        $.ajax({
                            type: "get",
                            url: url,
                            async: false,
                            success: function (res) {
                                if (res.success) {
                                    extra = res.data;
                                } else {
                                    top.layer.msg("获取下拉条件接口请求失败", { icon: 2, offset: '20px' });
                                }
                            }
                        });
                    } else {
                        extra = eval('(' + tempExtra + ')');
                    }
                    options += '<option value="">请选择</option>';
                    $.each(extra, function (i, v) {
                        options += '<option value="' + v.value + '">' + v.name + '</option>';
                    });
                } catch (e) {
                    extra = {};
                }
            }
            return selector_prifix + options + selector_suffix;
        }
    };
    exports('searchTable', obj); //注意，这里是模块输出的核心，模块名必须和use时的模块名一致
});